<?php
define('StorageDomain','eform');

if(!isset($_SESSION))
	session_start();
date_default_timezone_set ( "Etc/GMT-8" );


if(!class_exists('SaeStorage'))
{
	class SaeStorage
	{
		public function write($fakeDomain,$filename,$data)
		{
			file_put_contents($filename,$data);
		}
		public function read($fakeDomain,$filename)
		{
			return file_get_contents($filename);
		}
		public function delete($fakeDomain,$filename)
		{
			return unlink(filename);
		}
		public function fileExists($fakeDomain,$filename)
		{
			return file_exists(filename);
		}		
	}
}
$GLOBALS['S'] = new SaeStorage();
	
function Decode($str){
	$str=urldecode($str);
	$obj=json_decode($str,true);
	return $obj;
}

function GetPwd($id)
{
	return md5(md5('Azul_'.$id).'_Azul');
}

function GetFormFileName($id)
{
	$id=intval($id);
	$Pwd=GetPwd($id);
	return "form/{$Pwd}_{$id}.txt";	
}

function GetDataFileName($id)
{
	$id=intval($id);
	$Pwd=GetPwd($id);
	return GetDataFileNameByHash($Pwd);
}

function GetDataFileNameByHash($Pwd)
{
	$Pwd2=GetPwd($Pwd);
	return "form/{$Pwd}_{$Pwd2}.csv";	
}

function uniDecode($str){

	return preg_replace_callback(@'/\\\u[0-9A-Za-z]{4}/',unicode2utf8,$str);
}

function unicode2utf8($chars)
{
	$str='';
	foreach($chars as $val){
		$c = intval(substr($val,2),16);
		if($c < 0x80)	
			$str.= chr($c);	
		else if($c < 0x800)	
			$str.= chr( 0xc0 | ($c >> 6) ).chr( 0x80 | ($c & 0x3f) );	
		else if($c < 0x10000)	
			$str.= chr( 0xe0 | ($c >> 12) ).chr( 0x80 | (($c >> 6) & 0x3f) ).chr( 0x80 | ($c & 0x3f) );	
		else if($c < 0x200000)	
			$str.= chr(0xf0 | ($c >> 18)).chr(0x80 | (($c >> 12) & 0x3f)).chr(0x80 | (($c >> 6) & 0x3f)).chr(0x80 | ($c & 0x3f));		
	}
	return $str;
}
function ShowFormEditor($id,$hash) {
	$DefaultJson='{ "EmailFromRecipientRequired": false, "SignInToViewRequired": false, "FormTitle": "", "FormDescription": "", "Entries": [], "DomainCanShareOut": true, "RtlForm": false, "SummaryRestrictedToDomain": false, "PublicResponsesViewable": false, "DomainShowShareOutWarning": false, "CustomConfirmationMessage": "", "TouchedOnClientSide": false, "IncludeFormInEmail": true, "EditResponsesEnabled": false }';
	$content=file_get_contents('html/formedit.html');
	if($hash==GetPwd($id))
		$DefaultJson=$GLOBALS['S']->read(StorageDomain,GetFormFileName($id));
	$content=str_replace('[-id-]',$id,$content);
	$content=str_replace('[-hash-]',GetPwd($id),$content);
	$content=str_replace('[-FormJson-]',$DefaultJson,$content);	
	echo $content;
}
function ShowForm($id)
{
	$id=intval($id);
	
	$filename=GetFormFileName($id);	
	if(!$GLOBALS['S']->fileExists(StorageDomain,$filename))
		die('404 Not Found');
	$f=$GLOBALS['S']->read(StorageDomain,$filename);	
	$f=json_decode($f,true);
	$f['Entries']=RebuildEntries($f['Entries']);

	include('items.php');
	$StartEntryId=isset($_POST['nextpage'])?$_POST['nextpage']:-1;
	$pageHistory=isset($_POST['pagehistory'])?$_POST['pagehistory']:'';
	if(isset($_POST['back']))
	{
		$pages=split(',',$pageHistory);
		if(count($pages)>=2)
		{
			$StartEntryId=$pages[count($pages)-2];
			$pages=array_slice($pages,0,count($pages)-2);
			$pageHistory = implode(",", $pages); 
		}
	}	
	elseif(isset($_POST['continue']))
	{
		$gotoPage=GetGotoPage($f['Entries']);
		if($gotoPage!=-2)
			$StartEntryId=$gotoPage;
			SetValues();
	}
	elseif(isset($_POST['save']))
	{
		SetValues();
		ksort($_SESSION['TmpData']);
		$dataFileName=GetDataFileName($id);
		$data=$GLOBALS['S']->fileExists(StorageDomain,$dataFileName)?$GLOBALS['S']->read(StorageDomain,$dataFileName):'Empty';
		if($data=='Empty')
		{
			$headers=array();
			$headers[]='时间';
			$headers[]='IP';
			foreach ($_SESSION['TmpData'] as $key=>$value)	
			{				
				$headers[]=GetHeader($key,$f['Entries']);				
			}
			$data=implode(',', $headers);
			$data=chr(0xEF).chr(0xBB).chr(0xBF).$data;
		}
		$line=array();
		$line[]=date('Y-m-d H:i:s');
		$line[]=GetIP();
		foreach ($_SESSION['TmpData'] as $value)	
			{
				$line[]=$value;
			}
		$data.="\r\n".implode(',', $line);

		$GLOBALS['S']->write(StorageDomain,$dataFileName,$data);
		echo FormHeader($f['FormTitle'],$f['FormDescription']).'<br><h1>Thank You, 您已成功完成该问卷.</h1><br><br>'.FormFooter();
		exit;
	}
	$htmlForm=FormBody($f['Entries'],$StartEntryId,$pageHistory);

	echo FormHeader($f['FormTitle'],$f['FormDescription']).$htmlForm.FormFooter();
	
}

function GetHeader($EntryId,$Entries) 
{
	if(isset($Entries[$EntryId]))
		return $Entries[$EntryId]['QuestionTitle'];
	return $_SESSION['header.'.$EntryId];
	
}

function GetGotoPage($Entries)
{
	foreach ($_POST as $key=>$value)
	{
		$pos=strpos($key, 'GoToPage_');
		if($pos===false||$pos>0)
			continue;
		$strs=split('_',$key);	
		$entryId=$strs[1];	
			
		if(!isset($_POST["entry_{$entryId}_group"]))
			continue;
			$sValue=$_POST["entry_{$entryId}_group"];
		foreach ($Entries[$entryId]['Choices'] as $choice)		
			if($choice['Value']==$sValue)			
				return $choice['GoToPage'];	
	}
	return -2;//默认下一页		
}

function SetValues()
{
	$values=isset($_SESSION['TmpData'])?$_SESSION['TmpData']:array();
	foreach ($_POST as $key=>$value)
	{
		
	
		$pos=strpos($key, 'entry_');
		if($pos===false||$pos>0)
		{
			if(strpos($key, 'header.')!==false)			
				$values[$key]=$value;			
			continue;
		}
		$strs=explode('_',$key);	
		$entryId=$strs[1];
		$values["{$entryId}"]=is_array($value)?implode(' | ',$value):$value;	
	}
	$_SESSION['TmpData']=$values;
	return $values;
}

function RebuildEntries($Entries)
{
	$rtn=array();
	foreach ($Entries as $Entry)
	{
		$rtn[$Entry['EntryId']]=$Entry;
	}
	return $rtn;
}

function ShowDataReport($hash)
{
	if(!preg_match('/[0-9a-f]{32}/i', $hash))
		die('404 Not Found');
	$dataFileName=GetDataFileNameByHash($hash);
	if(!$GLOBALS['S']->fileExists(StorageDomain,$dataFileName))
		die('404 Not Found');
	header("Content-Type: application/csv; charset=UTF-8");
	header("Content-Disposition: attachment;Filename=export.csv");
	echo $GLOBALS['S']->read(StorageDomain,$dataFileName);	
}

function GetIP() {
	$ip = '';
	if (getenv ( 'HTTP_CLIENT_IP' ))
		$ip = getenv ( 'HTTP_CLIENT_IP' );
	elseif (getenv ( 'REMOTE_ADDR' ))
		$ip = getenv ( 'REMOTE_ADDR' );
	elseif (getenv ( 'HTTP_X_FORWARDED_FOR' ))
		$ip = getenv ( 'HTTP_X_FORWARDED_FOR' );	
	elseif (isset ( $HTTP_SERVER_VARS ))
		$ip = $HTTP_SERVER_VARS ['REMOTE_ADDR'];
	return $ip;
}
?>